package com.common.core.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @describe：创建线程池的工具类
 * @author：李勇
 * @date：2022/4/15
 * @return：
 */
public class ThreadPoolUtil {
    /**
     * 默认 CPU 核心数
     */
    private static int threadPoolSize = 0;

    static {
        // 获取服务器 CPU 核心数
        threadPoolSize = Runtime.getRuntime().availableProcessors();
        System.out.println(" CPU 核心数量:" + threadPoolSize);
    }

    public static int getThreadPoolSize() {
        return threadPoolSize;
    }

    /**
     * 线程工厂，用来创建线程
     */
    private static ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("thread-pool-demo-%d").build();

    /**
     * 设置线程池核心参数(IO 密集型) 核心线程数 = CPU 核数 * 2
     * 参数依次分别为上面的的7大参数，最后拒绝策略参数可以不写，则默认使用AbortPolicy
     */
    private static ThreadPoolExecutor threadPoolExecutorIO =
            new ThreadPoolExecutor(threadPoolSize, threadPoolSize * 2, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());

    /**
     * 设置线程池核心参数(CPU 密集型) 核心线程数 = CPU 核数 + 1 //  核心线程数 = CPU 核数 + 1
     */
    private static ThreadPoolExecutor threadPoolExecutorCPU =
            new ThreadPoolExecutor(threadPoolSize, threadPoolSize + 1, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());



    /**
     * 返回线程池对象
     *
     * @return
     */
    public static ThreadPoolExecutor getThreadPoolExecutorIO() {
        return threadPoolExecutorIO;
    }
    public static ThreadPoolExecutor getThreadPoolExecutorCPU() {
        return threadPoolExecutorCPU;
    }
}
